package com.zbkj.crmeb.merchant.admin.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.utils.RedisUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.utils.CrmebUtil;
import com.utils.PriceUtil;
import com.utils.ProductConvertUtil;
import com.utils.ProductUtil;
import com.zbkj.crmeb.agent.model.Agent;
import com.zbkj.crmeb.agent.service.AgentService;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.AreaTypeEnum;
import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.enums.StockAreaTempEnum;
import com.zbkj.crmeb.export.vo.ProductExcelVo;
import com.zbkj.crmeb.merchant.admin.service.MerAgentStoreProductService;
import com.zbkj.crmeb.store.dao.StoreProductDao;
import com.zbkj.crmeb.store.dao.StoreProductNormDao;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.request.StoreProductAttrValueRequest;
import com.zbkj.crmeb.store.request.StoreProductSearchRequest;
import com.zbkj.crmeb.store.response.StoreProductAttrValueResponse;
import com.zbkj.crmeb.store.response.StoreProductNormResponse;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.response.StoreProductTabsHeader;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.system.service.SystemAdminService;
import com.zbkj.crmeb.system.service.SystemConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author lvmd
 * @description MerAgentStoreProductServiceImpl 接口实现
 * @date 2022-02-22
 */
@Slf4j
@Service
public class MerAgentStoreProductServiceImpl extends ServiceImpl<StoreProductDao, StoreProduct> implements MerAgentStoreProductService {

    @Resource
    private PriceUtil priceUtil;
    @Resource
    private StoreProductDao storeProductDAO;
    @Resource
    private StoreProductNormDao storeProductNormDAO;
    @Resource
    private StoreProductAttrService attrService;
    @Resource
    private StoreProductAttrValueService storeProductAttrValueService;
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private StoreProductDescriptionService storeProductDescriptionService;
    @Resource
    private StoreProductAttrResultService storeProductAttrResultService;
    @Resource
    private ProductUtil productUtil;
    @Resource
    private ICategoryMatchService categoryMatchService;
    @Resource
    private StoreProductNormDescriptionService storeProductNormDescriptionService;
    @Resource
    private SystemAdminService systemAdminService;
    @Resource
    private AgentService agentService;
    @Resource
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private ProductConvertUtil productConvertUtil;
    @Autowired
    private RedisUtil redisUtil;
    /**
     * 商品列表
     *
     * @param request
     * @param pageParamRequest
     * @return
     */
    @Override
    public PageInfo<StoreProductResponse> listStoreProducts(StoreProductSearchRequest request, PageParamRequest pageParamRequest) {
        Agent agent = getAgent();
        Integer agentId = agent.getId();
        List<Integer> merIds = systemAdminService.getAdminAgentMerIds();
        if (CollectionUtils.isEmpty(merIds)) {
            return new PageInfo<>();
        }
        Page<StoreProduct> storeProductPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        Map<Integer, String> merchantNap = new HashMap<>(16);
        List<StoreProduct> storeProducts;
        if (Objects.isNull(request.getIsEurope())) {
            // 云仓
            LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = getQueryWrapper(request, agent);
            storeProducts = storeProductDAO.selectList(lambdaQueryWrapper);
        } else {
            // 自建处理
            request.setMerId(merIds);
            storeProducts = storeProductDAO.selectAgentProductList(request);
            // 查询商户
            List<ChannelMerchant> channelMerchantList = channelMerchantService.list(Wrappers.<ChannelMerchant>lambdaQuery()
                    .in(ChannelMerchant::getId, merIds)
                    .select(ChannelMerchant::getId, ChannelMerchant::getChannelName));
            merchantNap = channelMerchantList.stream().collect(Collectors.toMap(ChannelMerchant::getId, ChannelMerchant::getChannelName));

        }
        if (CollectionUtils.isEmpty(storeProducts)) {
            return CommonPage.copyPageInfo(storeProductPage, new ArrayList<>());
        }
        // 主图匹配
        productConvertUtil.convertProductImage(storeProducts);
        // 成本价
        priceUtil.calcAgentProductPrice(storeProducts, agentId,AreaTypeEnum.CN.getType());
        List<Integer> ids = storeProducts.stream().map(StoreProduct::getId).collect(Collectors.toList());
        // 处理attrvalue数据
        List<StoreProductAttrValue> attrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                .in(StoreProductAttrValue::getProductId, ids)
        );
        Map<Integer, List<StoreProductAttrValue>> attrValueMap = attrValues.stream().collect(Collectors.toMap(StoreProductAttrValue::getProductId,
                s -> {
                    List<StoreProductAttrValue> list = new ArrayList<StoreProductAttrValue>();
                    list.add(s);
                    return list;
                },
                (List<StoreProductAttrValue> value1, List<StoreProductAttrValue> value2) -> {
                    value1.addAll(value2);
                    return value1;
                }
        ));
        // 循环赋值
        List<StoreProductResponse> storeProductResponses = new ArrayList<>();
        for (StoreProduct product : storeProducts) {
            Integer id = product.getId();
            StoreProductResponse storeProductResponse = new StoreProductResponse();
            storeProductResponse.setMerchantName(merchantNap.get(product.getMerId()));
            BeanUtils.copyProperties(product, storeProductResponse);
            // 查询对应属性赋值
            if (attrValueMap.get(id) == null) {
                return null;
            }
            // 规格成本价
            priceUtil.calcAgentProductAttrValuePrice(attrValues, product, agentId, AreaTypeEnum.CN.getType(),product.getCateId());
            List<StoreProductAttrValue> values = attrValueMap.get(id);
            List<StoreProductAttrValueResponse> valueResponses = new ArrayList<>();
            for (StoreProductAttrValue value : values) {
                StoreProductAttrValueResponse valueResponse = new StoreProductAttrValueResponse();
                BeanUtils.copyProperties(value, valueResponse);
                valueResponses.add(valueResponse);
            }
            storeProductResponse.setAttrValue(valueResponses);
            // 通过原价算折扣率 ----处理
            if (storeProductResponse.getOtPrice() != null && storeProductResponse.getOtPrice().intValue() > 0) {
                BigDecimal bigDecimal = priceUtil.calcDiscount(storeProductResponse.getCost(), storeProductResponse.getOtPrice(), storeProductResponse.getExchangeRate());
                if (null != bigDecimal) {
                    storeProductResponse.setDiscount(bigDecimal.toString() + "折");
                }
            }
            storeProductResponses.add(storeProductResponse);
        }
        /******** end *******/
        return CommonPage.copyPageInfo(storeProductPage, storeProductResponses);
    }

    /**
     * 服务商云仓查询条件
     *
     * @param request
     * @return
     */
    private LambdaQueryWrapper<StoreProduct> getQueryWrapper(StoreProductSearchRequest request, Agent agent) {
        // 服务商 可见云仓商品
        List<Integer> brandIdsList = JSON.parseArray(agent.getBrandIds(), Integer.class);
        List<Integer> suppliersIdList = JSON.parseArray(agent.getSuppliersIds(), Integer.class);
        List<Integer> tempIdList = JSON.parseArray(agent.getTempId(), Integer.class);
        if (CollectionUtils.isEmpty(request.getBrandIds())) {
            request.setBrandIds(brandIdsList);
        }
        if (CollectionUtils.isEmpty(request.getSupplierIds())) {
            request.setSupplierIds(suppliersIdList);
        }
        if (CollectionUtils.isEmpty(request.getStockAreas())) {
            request.setStockAreas(tempIdList);
        }

        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //类型搜索
        switch (request.getType()) {
            case 1:
                //出售中（已上架）
                lambdaQueryWrapper.eq(StoreProduct::getIsShow, true);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                // 库存为0的商品不显示在出售中列表
                lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
                break;
            case 2:
                //仓库中（未上架）
                lambdaQueryWrapper.eq(StoreProduct::getIsShow, false);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            case 3:
                //已售罄
                lambdaQueryWrapper.le(StoreProduct::getStock, 0);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            case 4:
                //警戒库存
                //Integer stock = Integer.parseInt(systemConfigService.getValueByKey("store_stock"));
                lambdaQueryWrapper.le(StoreProduct::getStock, 2);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            case 5:
                //回收站
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, true);
                break;
            default:
                break;
        }

        //关键字搜索
        if (!StringUtils.isBlank(request.getKeywords())) {
            lambdaQueryWrapper.and(i -> i.or().eq(NumberUtil.isInteger(request.getKeywords()),StoreProduct::getId, request.getKeywords())
                    .or().like(StoreProduct::getStoreName, request.getKeywords())
//                    .or().like(StoreProduct::getStoreInfo, request.getKeywords())
                    .or().like(StoreProduct::getKeyword, request.getKeywords())
                    .or().like(StoreProduct::getBarCode, request.getKeywords()));
        }
        if (BooleanUtil.isTrue(request.getIsBest())) {
            lambdaQueryWrapper.eq(StoreProduct::getIsBest, true);
        }
        //判断是否供应商筛选
        if (request.getSupplierId() != null) {
            lambdaQueryWrapper.eq(StoreProduct::getSuppliersId, request.getSupplierId());
        }
        if (CollectionUtils.isNotEmpty(request.getSupplierIds())) {
            lambdaQueryWrapper.in(StoreProduct::getSuppliersId, request.getSupplierIds());
        }
//        if (CollectionUtils.isNotEmpty(request.getMerId())) {
//            lambdaQueryWrapper.in(StoreProduct::getMerId, request.getMerId());
//        }
        if (CollectionUtils.isNotEmpty(request.getStockAreas())) {
            lambdaQueryWrapper.in(StoreProduct::getTempId,request.getStockAreas());
        }
        if (StringUtils.isNotBlank(request.getBrandId())) {
            lambdaQueryWrapper.eq(StoreProduct::getBrandId, request.getBrandId());
        }
        if (CollectionUtils.isNotEmpty(request.getBrandIds())) {
            lambdaQueryWrapper.in(StoreProduct::getBrandId, request.getBrandIds());
        }
        if (StringUtils.isNotBlank(request.getCateId())) {
            List<Integer> cateIds = categoryMatchService.getThreeChildVoListByPid(Integer.parseInt(request.getCateId())).stream().map(CategoryMatch::getId).collect(Collectors.toList());
            String cateIdStr = StringUtils.join(cateIds, ",");
            lambdaQueryWrapper.apply(CrmebUtil.getFindInSetSql("cate_id", cateIdStr));
        }
        if (CollectionUtils.isNotEmpty(request.getCateIds())) {
            List<Integer> cateIds = new ArrayList<>();
            request.getCateIds().forEach(cateId -> cateIds.addAll(categoryMatchService.getThreeChildVoListByPid(cateId).stream().map(CategoryMatch::getId).collect(Collectors.toList())));
            String cateIdStr = StringUtils.join(cateIds, ",");
            lambdaQueryWrapper.apply(CrmebUtil.getFindInSetSql("cate_id", cateIdStr));
        }
//        if (StringUtils.isNotBlank(request.getZoneId())) {
//            List<StoreZoneProduct> storeZoneProduct = storeZoneProductService.list(Wrappers.<StoreZoneProduct>lambdaQuery().eq(StoreZoneProduct::getZoneId, request.getZoneId()));
//            List<Integer> productIds = storeZoneProduct.stream().map(StoreZoneProduct::getProductId).distinct().collect(Collectors.toList());
//            productIds.add(0);
//            lambdaQueryWrapper.in(StoreProduct::getId, productIds);
//        }

        // 新增条件最低高价格 最大小库存
        if (request.getMinPrice() != null && request.getMaxPrice() == null) {
            lambdaQueryWrapper.ge(StoreProduct::getPrice, request.getMinPrice());
        } else if (request.getMinPrice() == null && request.getMaxPrice() != null) {
            lambdaQueryWrapper.le(StoreProduct::getPrice, request.getMaxPrice());
        } else if (request.getMinPrice() != null && request.getMaxPrice() != null) {
            lambdaQueryWrapper.between(StoreProduct::getPrice, request.getMinPrice(), request.getMaxPrice());
        }
        if (request.getMinStock() != null && request.getMaxStock() == null) {
            lambdaQueryWrapper.ge(StoreProduct::getStock, request.getMinStock());
        } else if (request.getMinStock() == null && request.getMaxStock() != null) {
            lambdaQueryWrapper.le(StoreProduct::getStock, request.getMaxStock());
        } else if (request.getMinStock() != null && request.getMaxStock() != null) {
            lambdaQueryWrapper.between(StoreProduct::getStock, request.getMinStock(), request.getMaxStock());
        }
//        if (null != request.getIsEurope()) {
//            lambdaQueryWrapper.eq(StoreProduct :: getIsEurope, ProductTypeEnum.INSIDE.getCode());
//        }
//        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(merIds), StoreProduct::getMerId, merIds);
        if (null != request.getSeasonCode()) {
            if ("-1".equals(request.getSeasonCode())) {
                lambdaQueryWrapper.isNull(StoreProduct::getSeasonCode);
            } else {
                lambdaQueryWrapper.likeRight(StoreProduct::getSeasonCode, request.getSeasonCode());
            }
        }
//        if (null != request.getIsNorm()) {
//            if (request.getIsNorm()) {
//                lambdaQueryWrapper.isNotNull(StoreProduct::getNormId);
//            } else if (!request.getIsNorm()) {
//                lambdaQueryWrapper.isNull(StoreProduct::getNormId);
//            }
//        }
        if (CollectionUtils.isNotEmpty(request.getIsNotEurope())) {
            lambdaQueryWrapper.and(e->e.notIn(StoreProduct :: getIsEurope, request.getIsNotEurope())
                    .or(i->i.eq(StoreProduct::getIsEurope,1).isNotNull(StoreProduct::getConvertIsEurope)));
//            lambdaQueryWrapper.notIn(StoreProduct::getIsEurope, request.getIsNotEurope());
        }
//        if (ObjectUtils.isNotEmpty(request.getCreateTimeStart()) && ObjectUtils.isNotEmpty(request.getCreateTimeEnd())) {
//            lambdaQueryWrapper.between(StoreProduct::getAddTime, DateUtil.strToDate(request.getCreateTimeStart(), Constants.DATE_FORMAT_DATE).getTime() / 1000, DateUtil.strToDate(request.getCreateTimeEnd(), Constants.DATE_FORMAT_DATE).getTime() / 1000);
//        }
        //折扣查询
        if (request.getMinDiscount() != null && request.getMaxDiscount() == null) {
            lambdaQueryWrapper.apply("CEILING( source_cost / (ot_price * exchange_rate)*100) / 10 >= {0} ", request.getMinDiscount());
        } else if (request.getMinDiscount() == null && request.getMaxDiscount() != null) {
            lambdaQueryWrapper.apply("CEILING( source_cost / (ot_price * exchange_rate)*100) / 10 <= {0} ", request.getMaxDiscount());
        } else if (request.getMinDiscount() != null && request.getMaxDiscount() != null) {
            lambdaQueryWrapper.apply("CEILING( source_cost / (ot_price * exchange_rate)*100) / 10 BETWEEN  {0} and {1} ", request.getMinDiscount(), request.getMaxDiscount());
        }
//        lambdaQueryWrapper.orderByDesc(StoreProduct::getId);
        // 成本价折扣排序
        if (request.getCostSort() != null) {
            String value = request.getCostSort() == 0 ? "ASC" : "DESC";
            lambdaQueryWrapper.last("ORDER BY CEILING( source_cost / (ot_price * exchange_rate)*100) / 10 " + value);
        } else {
            lambdaQueryWrapper.orderByDesc(StoreProduct::getLastPushTime);
        }
        return lambdaQueryWrapper;
    }

    /**
     * 云仓商品详情
     *
     * @param id
     * @param id
     * @return
     */
    @Override
    public StoreProductNormResponse getSupplierByProductId(Integer id, Integer merId) {
        StoreProductNormResponse response = new StoreProductNormResponse();
        StoreProduct product = storeProductDAO.selectById(id);
        Integer normId = product.getNormId();
        if (null != normId) {
            response.setProductNorm(storeProductNormDAO.selectById(normId));
            response.setProducts(listByNormId(normId, merId));
            String description = storeProductNormDescriptionService.getProductNormDesc(id);
            if (Objects.nonNull(response.getProductNorm()) && StringUtils.isNotBlank(description)) {
                response.getProductNorm().setStoreInfo(description);
            }
        } else {
            StoreProductResponse storeProductResponse = getByProductId(id, merId);
            List<StoreProductResponse> storeProductResponses = Arrays.asList(storeProductResponse);
            response.setProducts(storeProductResponses);

            // 使用自建商品属性赋值到标准商品上
            if (CollectionUtils.isNotEmpty(storeProductResponses)) {
                StoreProductNorm norm = new StoreProductNorm();
                BeanUtils.copyProperties(storeProductResponses.get(0), norm);
                response.setProductNorm(norm);
            }
        }

        return response;
    }

    private List<StoreProductResponse> listByNormId(Integer id, Integer merId) {
        List<StoreProduct> storeProducts = storeProductDAO.selectList(Wrappers.<StoreProduct>lambdaQuery()
                .eq(StoreProduct::getNormId, id)
                .eq(StoreProduct::getIsDel, false)
        );
        if (CollectionUtils.isEmpty(storeProducts)) {
            return null;
        }
        // 匹配详情属性
        productConvertUtil.convertProduct(storeProducts);
//        Map<Integer, String> productDescMap = storeProductDescriptionService.getProductDescMap(storeProducts.stream().map(StoreProduct::getId).collect(Collectors.toList()));
        List<StoreProductResponse> storeProductResponses = new ArrayList<>();
        for (StoreProduct storeProduct : storeProducts) {
            StoreProductResponse storeProductResponse = new StoreProductResponse();
            BeanUtils.copyProperties(storeProduct, storeProductResponse);
            // 暂写死固定自营小程序私域图权限
			if (null != merId && 18 != merId && 30 != merId/* && 45 != merId && 47 != merId*/) {
            	storeProductResponse.setMt(null);
            	storeProductResponse.setSp2(null);
            }

            storeProductResponse.setStockArea(StockAreaTempEnum.getByTempId(storeProduct.getTempId()).getStockAreaCode());
            //发货时间
            storeProductResponse.setDeliveryTime(productUtil.getDeliveryTimeByTempId(storeProduct.getTempId(), storeProduct.getIsEurope(), storeProduct.getMerId(), storeProduct.getId()));
            //收货时间
            String receivingTime = productUtil.getReceivingTime(storeProductResponse.getStockArea(), storeProductResponse.getIsEurope(), storeProduct.getMerId(), storeProduct.getId());
            storeProductResponse.setReceivingTime(receivingTime);
            // 设置sku属性
            storeProductResponse.setAttr(attrService.getByProductId(storeProduct.getId()));
            List<StoreProductAttrValue> storeProductAttrValues = storeProductAttrValueService.getListByProductId(storeProduct.getId());
            if (CollectionUtils.isEmpty(storeProductAttrValues)) {
                continue;
            }

            if (storeProductResponse.getPrice() == null || storeProductResponse.getOtPrice() == null) {
                calcPriceForAttrValues(storeProductAttrValues, storeProductResponse);
            }
            // 根据attrValue生成前端所需的数据
            List<HashMap<String, Object>> attrValues = new ArrayList<>();
            Map<String, StoreProductAttrValue> valMap = new HashMap<>();
            for (StoreProductAttrValue spav : storeProductAttrValues) {
                valMap.put(spav.getAttrValue(), spav);
            }
            if (storeProduct.getSpecType()) {
                // 后端多属性用于编辑
                StoreProductAttrResult attrResult = storeProductAttrResultService.getByProductId(storeProduct.getId());
                //PC 端生成skuAttrInfo
                List<StoreProductAttrValueRequest> storeProductAttrValueRequests = com.alibaba.fastjson.JSONObject.parseArray(attrResult.getResult(), StoreProductAttrValueRequest.class);
                if (null != storeProductAttrValueRequests) {
                    for (int i = 0; i < storeProductAttrValueRequests.size(); i++) {
                        StoreProductAttrValueRequest storeProductAttrValueRequest = storeProductAttrValueRequests.get(i);
                        StoreProductAttrValue attrVal = valMap.get(JSON.toJSONString(storeProductAttrValueRequest.getAttrValue()));
                        if (null == attrVal) {
                            continue;
                        }
                        HashMap<String, Object> attrValue = new HashMap<>();
                        attrValue.put("image", storeProductAttrValueRequest.getImage());
                        attrValue.put("cost", storeProductAttrValueRequest.getCost());
                        attrValue.put("price", storeProductAttrValueRequest.getPrice());
                        attrValue.put("otPrice", storeProductAttrValueRequest.getOtPrice());
                        // 不能显示result里的库存
                        attrValue.put("stock", attrVal.getStock());
                        attrValue.put("barCode", storeProductAttrValueRequest.getBarCode());
                        attrValue.put("weight", storeProductAttrValueRequest.getWeight());
                        attrValue.put("volume", storeProductAttrValueRequest.getVolume());
                        attrValue.put("suk", attrVal.getSuk());
                        attrValue.put("attrValue", JSON.parse(attrVal.getAttrValue()));
                        attrValue.put("brokerage", storeProductAttrValueRequest.getBrokerage());
                        attrValue.put("brokerage_two", storeProductAttrValueRequest.getBrokerageTwo());
                        Iterator<Map.Entry<String, String>> iterator = storeProductAttrValueRequest.getAttrValue().entrySet().iterator();
                        int j = 0;
                        while (iterator.hasNext()) {
                            Map.Entry<String, String> entry = iterator.next();
                            attrValue.put("value" + j, entry.getValue());
                            j += 1;
                        }
                        attrValues.add(attrValue);
                    }
                }
            }

            // H5 端用于生成skuList
            List<StoreProductAttrValueResponse> sPAVResponses = new ArrayList<>();
            for (StoreProductAttrValue storeProductAttrValue : storeProductAttrValues) {
                StoreProductAttrValueResponse atr = new StoreProductAttrValueResponse();
                BeanUtils.copyProperties(storeProductAttrValue, atr);
                sPAVResponses.add(atr);
            }

//            if (StringUtils.isNotBlank(productDescMap.get(storeProduct.getId()))) {
//                storeProductResponse.setStoreInfo(productDescMap.get(storeProduct.getId()));
//            }
            storeProductResponse.setAttrValues(attrValues);
            storeProductResponse.setAttrValue(sPAVResponses);

            storeProductResponses.add(storeProductResponse);
        }

        return storeProductResponses;
    }

    /**
     * 计算产品属性之中最大和最小的价格，新增和编辑使用
     *
     * @param attrValues   分析的参数
     * @param storeProduct 当前操作的产品
     */
    private void calcPriceForAttrValues(List<StoreProductAttrValue> attrValues, StoreProductResponse storeProduct) {

        double sellPrice = attrValues.stream().mapToDouble(e -> e.getPrice().doubleValue()).min().getAsDouble();
        double otPrice = attrValues.stream().mapToDouble(e -> e.getOtPrice().doubleValue()).min().getAsDouble();

        int stock = attrValues.stream().mapToInt(e -> e.getStock()).sum();
        storeProduct.setPrice(BigDecimal.valueOf(sellPrice));
        storeProduct.setOtPrice(BigDecimal.valueOf(otPrice));
        storeProduct.setStock(stock);
    }

    /**
     * 商品详情
     *
     * @param id
     * @return
     */
    @Override
    public StoreProductResponse getByProductId(Integer id, Integer merId) {
        Integer agentId = systemAdminService.getAdminAgentId();
        StoreProduct storeProduct = storeProductDAO.selectById(id);
        if (null == storeProduct) {
            throw new CrmebException("未找到对应商品信息");
        }
        // 匹配详情属性
        productConvertUtil.convertProduct(storeProduct);
        // 加价计算规则
        priceUtil.calcAgentProductPrice(Collections.singletonList(storeProduct), agentId,AreaTypeEnum.CN.getType());
        StoreProductResponse storeProductResponse = new StoreProductResponse();
        BeanUtils.copyProperties(storeProduct, storeProductResponse);
        // 暂写死固定自营小程序私域图权限
		if (null != merId && 18 != merId && 30 != merId/* && 45 != merId && 47 != merId*/) {
        	storeProductResponse.setMt(null);
        	storeProductResponse.setSp2(null);
        }
        // 商品详情
        StoreProductDescription sd = storeProductDescriptionService.getOne(new LambdaQueryWrapper<StoreProductDescription>()
                .eq(StoreProductDescription::getProductId, storeProduct.getId())
                .last("LIMIT 1")
        );
        if (null != sd) {
            storeProductResponse.setStoreInfo(StringUtils.isNotBlank(sd.getDescription())  ? sd.getDescription() : storeProductResponse.getStoreInfo());
        }

        //发货时间
        storeProductResponse.setDeliveryTime(productUtil.getDeliveryTimeByTempId(storeProduct.getTempId(), storeProduct.getIsEurope(), storeProduct.getMerId(), storeProduct.getId()));
        //收货时间
        storeProductResponse.setStockArea(StockAreaTempEnum.getByTempId(storeProduct.getTempId()).getStockAreaCode());
        String receivingTime = productUtil.getReceivingTime(storeProductResponse.getStockArea(), storeProductResponse.getIsEurope(), storeProduct.getMerId(), storeProduct.getId());
        storeProductResponse.setReceivingTime(receivingTime);
        // 设置sku属性
        storeProductResponse.setAttr(attrService.getByProductId(storeProduct.getId()));
        List<StoreProductAttrValue> storeProductAttrValues = storeProductAttrValueService.getListByProductId(storeProduct.getId());

        if (CollectionUtils.isEmpty(storeProductAttrValues)) {
            return storeProductResponse;
        }

        // 根据attrValue生成前端所需的数据
        List<HashMap<String, Object>> attrValues = new ArrayList<>();
        Map<String, StoreProductAttrValue> valMap = new HashMap<>();
        // 加价计算规则
//        priceUtil.calcAgentProductAttrValuePrice(storeProductAttrValues, storeProduct, agentId);
        ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(merId);
        boolean freeShipping = freeShipping(storeProduct.getSuppliersId(), channelMerchant.getId());
//        priceUtil.calcAgentProductAttrValuePrice(storeProduct.getIsEurope(), storeProduct.getTempId(),AreaTypeEnum.CN.getType(),channelMerchant,freeShipping,storeProduct.getCateId(),storeProduct.getSuppliersName(),false);
        priceUtil.calcAgentProductAttrValuePrice(storeProductAttrValues, storeProduct, agentId,AreaTypeEnum.CN.getType(),storeProduct.getCateId());
        for (StoreProductAttrValue spav : storeProductAttrValues) {
            valMap.put(spav.getAttrValue(), spav);
        }
        if (storeProduct.getSpecType()) {
            // 后端多属性用于编辑
            StoreProductAttrResult attrResult = storeProductAttrResultService.getByProductId(storeProduct.getId());
            //PC 端生成skuAttrInfo
            List<StoreProductAttrValueRequest> storeProductAttrValueRequests = com.alibaba.fastjson.JSONObject.parseArray(attrResult.getResult(), StoreProductAttrValueRequest.class);
            if (null != storeProductAttrValueRequests) {
                for (int i = 0; i < storeProductAttrValueRequests.size(); i++) {
                    StoreProductAttrValueRequest storeProductAttrValueRequest = storeProductAttrValueRequests.get(i);
                    StoreProductAttrValue attrVal = valMap.get(JSON.toJSONString(storeProductAttrValueRequest.getAttrValue()));
                    if (null == attrVal) {
                        continue;
                    }
                    HashMap<String, Object> attrValue = new HashMap<>();
                    attrValue.put("image", storeProductAttrValueRequest.getImage());
                    attrValue.put("cost", attrVal.getCost().setScale(2, BigDecimal.ROUND_UP));
                    attrValue.put("taxAndSecondPrice", attrVal.getTaxAndSecondPrice() == null ? BigDecimal.ZERO : attrVal.getTaxAndSecondPrice().setScale(2, BigDecimal.ROUND_UP));
                    attrValue.put("price", attrVal.getPrice().setScale(2, BigDecimal.ROUND_UP));
                    attrValue.put("otPrice", storeProductAttrValueRequest.getOtPrice());
                    // 不能显示result里的库存
                    attrValue.put("stock", attrVal.getStock());
                    attrValue.put("barCode", storeProductAttrValueRequest.getBarCode());
                    attrValue.put("weight", storeProductAttrValueRequest.getWeight());
                    attrValue.put("volume", storeProductAttrValueRequest.getVolume());
                    attrValue.put("suk", attrVal.getSuk());
                    attrValue.put("attrValue", JSON.parse(attrVal.getAttrValue()));
                    attrValue.put("brokerage", storeProductAttrValueRequest.getBrokerage());
                    attrValue.put("brokerage_two", storeProductAttrValueRequest.getBrokerageTwo());
                    attrValue.put("sourceSkuId", storeProductAttrValueRequest.getSourceSkuId());
                    Iterator<Map.Entry<String, String>> iterator = storeProductAttrValueRequest.getAttrValue().entrySet().iterator();
                    int j = 0;
                    while (iterator.hasNext()) {
                        Map.Entry<String, String> entry = iterator.next();
                        attrValue.put("value" + j, entry.getValue());
                        j += 1;
                    }
                    attrValues.add(attrValue);
                }
            }
        }

        // H5 端用于生成skuList
        List<StoreProductAttrValueResponse> sPAVResponses = new ArrayList<>();
        for (StoreProductAttrValue storeProductAttrValue : storeProductAttrValues) {
            StoreProductAttrValueResponse atr = new StoreProductAttrValueResponse();
            BeanUtils.copyProperties(storeProductAttrValue, atr);
            atr.setPrice(atr.getPrice().setScale(2, RoundingMode.HALF_UP));
            //tax
            atr.setTaxAndSecondPrice(atr.getTaxAndSecondPrice() == null ? BigDecimal.ZERO : atr.getTaxAndSecondPrice().setScale(2, RoundingMode.HALF_UP));
            atr.setCost(atr.getCost().setScale(2, RoundingMode.HALF_UP));
            atr.setDeliveryTime(productUtil.getDeliveryTimeByTempId(storeProductAttrValue.getTempId(), storeProduct.getIsEurope(), storeProduct.getMerId(), storeProduct.getId()));
            atr.setReceivingTime(productUtil.getReceivingTime(storeProductAttrValue.getTempId(), storeProduct.getIsEurope(), storeProduct.getMerId(), storeProduct.getId()));
            sPAVResponses.add(atr);
        }
        storeProductResponse.setAttrValues(attrValues);
        storeProductResponse.setAttrValue(sPAVResponses);

        return storeProductResponse;
    }

    @Override
    public List<StoreProductTabsHeader> getTabsHeader(int type) {

        List<StoreProductTabsHeader> headers = new ArrayList<>();
        StoreProductTabsHeader header1 = new StoreProductTabsHeader(0, "出售中商品", 1);
        StoreProductTabsHeader header2 = new StoreProductTabsHeader(0, "仓库中商品", 2);
        StoreProductTabsHeader header3 = new StoreProductTabsHeader(0, "已经售馨商品", 3);
        StoreProductTabsHeader header4 = new StoreProductTabsHeader(0, "警戒库存", 4);
        StoreProductTabsHeader header5 = new StoreProductTabsHeader(0, "商品回收站", 5);
        headers.add(header1);
        headers.add(header2);
        headers.add(header3);
        headers.add(header4);
        headers.add(header5);

        List<Integer> merIds = systemAdminService.getAdminAgentMerIds();
        if (CollectionUtils.isEmpty(merIds)) {
            return headers;
        }
        Agent agent = getAgent();
        List<Integer> brandIdsList = JSON.parseArray(agent.getBrandIds(), Integer.class);
        List<Integer> suppliersIdList = JSON.parseArray(agent.getSuppliersIds(), Integer.class);
        List<Integer> tempIdList = JSON.parseArray(agent.getTempId(), Integer.class);

        boolean isEurope = 1 == type;
        for (StoreProductTabsHeader h : headers) {
            // 自建列表
            if (isEurope) {
                StoreProductSearchRequest request = new StoreProductSearchRequest();
                request.setMerId(merIds);
                request.setType(h.getType());
                Long count = storeProductDAO.countAgentStoreProduct(request);
                h.setCount(count.intValue());
                continue;
            }
            // 云仓
            LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.and(e->e.eq(StoreProduct :: getIsEurope, ProductTypeEnum.INSIDE.getCode())
                    .or(i->i.eq(StoreProduct::getIsEurope,1).isNotNull(StoreProduct::getConvertIsEurope)));
//            List<Integer> productTypes = Arrays.asList(ProductTypeEnum.INSIDE.getCode());
//            lambdaQueryWrapper.notIn(StoreProduct::getIsEurope, productTypes);
            // 服务商所属
            lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(brandIdsList), StoreProduct::getBrandId, brandIdsList);
            lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(suppliersIdList), StoreProduct::getSuppliersId, suppliersIdList);
            lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(tempIdList), StoreProduct::getTempId, tempIdList);
            switch (h.getType()) {
                case 1:
                    //出售中（已上架）
                    lambdaQueryWrapper.eq(StoreProduct::getIsShow, true);
                    lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                    // 库存为0的商品不显示在出售中列表
                    lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
                    break;
                case 2:
                    //仓库中（未上架）
                    lambdaQueryWrapper.eq(StoreProduct::getIsShow, false);
                    lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                    break;
                case 3:
                    //已售罄
                    lambdaQueryWrapper.le(StoreProduct::getStock, 0);
                    lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                    break;
                case 4:
                    //警戒库存
                    Integer stock = Integer.parseInt(systemConfigService.getValueByKey("store_stock"));
                    lambdaQueryWrapper.le(StoreProduct::getStock, stock);
                    lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                    break;
                case 5:
                    //回收站
                    lambdaQueryWrapper.eq(StoreProduct::getIsDel, true);
                    break;
                default:
                    break;
            }
            lambdaQueryWrapper.orderByAsc(StoreProduct::getId);
            Page<Object> page = PageHelper.startPage(1, 1);
            storeProductDAO.selectList(lambdaQueryWrapper);
            h.setCount(new Long(page.getTotal()).intValue());

        }

        return headers;
    }

    /**
     * 获取agent
     *
     * @return
     */
    private Agent getAgent() {
        Integer agentId = systemAdminService.getAdminAgentId();
        if (Objects.isNull(agentId)) {
            throw new CrmebException("当前账号无权限查看");
        }
        Agent agent = agentService.getById(agentId);
        if (Objects.isNull(agent)) {
            throw new CrmebException("当前服务商不存在");
        }
        return agent;
    }

    /**
     * 商品导出
     *
     * @param request
     * @param pageParamRequest
     * @return
     */
    @Override
    public List<ProductExcelVo> getExportList(StoreProductSearchRequest request, PageParamRequest pageParamRequest) {
        List<Integer> merIds = systemAdminService.getAdminAgentMerIds();
        if (CollectionUtils.isEmpty(merIds)) {
            return new ArrayList<ProductExcelVo>();
        }
        Agent agent = getAgent();
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = getQueryWrapper(request, agent);
        String sqlSegment = lambdaQueryWrapper.getSqlSegment();
        HashMap<String, Object> ew = new HashMap<String, Object>() {{
            put("paramNameValuePairs", lambdaQueryWrapper.getParamNameValuePairs());
        }};
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<ProductExcelVo> list = storeProductDAO.selectExportList(sqlSegment, ew);
        return list;
    }

    public boolean freeShipping(Integer suppliersId, Integer merId) {
        ChannelMerchant relatedMerchant = getRelatedMerchant(suppliersId, merId);
        if(Objects.nonNull(relatedMerchant) && StringUtils.isNotBlank(relatedMerchant.getFreeIds())){
            return Arrays.asList(relatedMerchant.getFreeIds().split(",")).contains(merId.toString());
        }
        return false;
    }

    public ChannelMerchant getRelatedMerchant(Integer suppliersId, Integer merId) {
        if(null != merId && null != suppliersId){
            ChannelMerchant channelMerchant = channelMerchantService.getMerchantByRelated(3,"[" + suppliersId + "]");
            if (Objects.isNull(channelMerchant)){
                channelMerchant = channelMerchantService.getOne(Wrappers.<ChannelMerchant>lambdaQuery()
                        .eq(ChannelMerchant::getChannelType, 3)
                        .eq(ChannelMerchant::getSuppliersIds, "[" + suppliersId + "]")
                        .last("LIMIT 1")
                );
                if (Objects.nonNull(channelMerchant)){
                    redisUtil.set(Constants.CHANNEL_MERCHANT + channelMerchant.getId(),channelMerchant,24L, TimeUnit.HOURS);
                }
            }
            return channelMerchant;
        }
        return null;
    }
}
